package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.markdown.requset.MarkdownPreviewRequest;
import com.blog.cmrpersonalblog.dto.markdown.respnose.MarkdownPreviewResponse;
import com.blog.cmrpersonalblog.service.MarkdownService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

/**
 * Markdown处理控制器
 * 提供Markdown转换和预览功能
 */
@Slf4j
@RestController
@RequestMapping("/api/markdown")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckLogin
@Validated
public class MarkdownController {

   @Resource
    private MarkdownService markdownService;

    /**
     * Markdown预览
     */
    @PostMapping("/preview")
    public Result<MarkdownPreviewResponse> preview(@RequestBody @Valid MarkdownPreviewRequest request) {
        log.info("Markdown预览请求: contentLength={}, theme={}", 
                request.getContent().length(), request.getTheme());
        
        try {
            MarkdownPreviewResponse response = markdownService.preview(request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("Markdown预览失败", e);
            return Result.error("预览失败：" + e.getMessage());
        }
    }

    /**
     * 将Markdown转换为HTML
     */
    @PostMapping("/convert")
    public Result<String> convertToHtml(@RequestBody @NotBlank String markdownContent) {
        log.info("Markdown转HTML请求: contentLength={}", markdownContent.length());
        
        try {
            String htmlContent = markdownService.convertToHtml(markdownContent);
            return Result.success(htmlContent);
        } catch (Exception e) {
            log.error("Markdown转HTML失败", e);
            return Result.error("转换失败：" + e.getMessage());
        }
    }

    /**
     * 提取文章目录
     */
    @PostMapping("/toc")
    public Result<String> extractTableOfContents(@RequestBody @NotBlank String markdownContent) {
        log.info("提取目录请求: contentLength={}", markdownContent.length());
        
        try {
            String toc = markdownService.extractTableOfContents(markdownContent);
            return Result.success(toc);
        } catch (Exception e) {
            log.error("提取目录失败", e);
            return Result.error("提取目录失败：" + e.getMessage());
        }
    }

    /**
     * 计算字数
     */
    @PostMapping("/word-count")
    public Result<Integer> calculateWordCount(@RequestBody @NotBlank String markdownContent) {
        log.info("计算字数请求: contentLength={}", markdownContent.length());
        
        try {
            Integer wordCount = markdownService.calculateWordCount(markdownContent);
            return Result.success(wordCount);
        } catch (Exception e) {
            log.error("计算字数失败", e);
            return Result.error("计算字数失败：" + e.getMessage());
        }
    }

    /**
     * 生成文章摘要
     */
    @PostMapping("/summary")
    public Result<String> generateSummary(@RequestBody @NotBlank String markdownContent,
                                         @RequestParam(defaultValue = "200") Integer maxLength) {
        log.info("生成摘要请求: contentLength={}, maxLength={}", markdownContent.length(), maxLength);
        
        try {
            String summary = markdownService.generateSummary(markdownContent, maxLength);
            return Result.success(summary);
        } catch (Exception e) {
            log.error("生成摘要失败", e);
            return Result.error("生成摘要失败：" + e.getMessage());
        }
    }

    /**
     * 清理HTML标签
     */
    @PostMapping("/strip-html")
    public Result<String> stripHtmlTags(@RequestBody @NotBlank String htmlContent) {
        log.info("清理HTML标签请求: contentLength={}", htmlContent.length());
        
        try {
            String plainText = markdownService.stripHtmlTags(htmlContent);
            return Result.success(plainText);
        } catch (Exception e) {
            log.error("清理HTML标签失败", e);
            return Result.error("清理失败：" + e.getMessage());
        }
    }

    /**
     * 批量处理Markdown内容
     */
    @PostMapping("/batch-process")
    public Result<BatchProcessResponse> batchProcess(@RequestBody @Valid BatchProcessRequest request) {
        log.info("批量处理Markdown请求: contentLength={}", request.getMarkdownContent().length());
        
        try {
            BatchProcessResponse response = new BatchProcessResponse();
            
            // 转换为HTML
            if (request.isConvertToHtml()) {
                response.setHtmlContent(markdownService.convertToHtml(request.getMarkdownContent()));
            }
            
            // 提取目录
            if (request.isExtractToc()) {
                response.setTableOfContents(markdownService.extractTableOfContents(request.getMarkdownContent()));
            }
            
            // 计算字数
            if (request.isCalculateWordCount()) {
                response.setWordCount(markdownService.calculateWordCount(request.getMarkdownContent()));
                response.setReadingTime(markdownService.calculateReadingTime(response.getWordCount()));
            }
            
            // 生成摘要
            if (request.isGenerateSummary()) {
                response.setSummary(markdownService.generateSummary(request.getMarkdownContent(), request.getSummaryMaxLength()));
            }
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("批量处理Markdown失败", e);
            return Result.error("批量处理失败：" + e.getMessage());
        }
    }

    /**
     * 批量处理请求DTO
     */
    public static class BatchProcessRequest {
        @NotBlank(message = "Markdown内容不能为空")
        private String markdownContent;
        
        private boolean convertToHtml = true;
        private boolean extractToc = false;
        private boolean calculateWordCount = true;
        private boolean generateSummary = false;
        private Integer summaryMaxLength = 200;

        // Getters and Setters
        public String getMarkdownContent() { return markdownContent; }
        public void setMarkdownContent(String markdownContent) { this.markdownContent = markdownContent; }
        
        public boolean isConvertToHtml() { return convertToHtml; }
        public void setConvertToHtml(boolean convertToHtml) { this.convertToHtml = convertToHtml; }
        
        public boolean isExtractToc() { return extractToc; }
        public void setExtractToc(boolean extractToc) { this.extractToc = extractToc; }
        
        public boolean isCalculateWordCount() { return calculateWordCount; }
        public void setCalculateWordCount(boolean calculateWordCount) { this.calculateWordCount = calculateWordCount; }
        
        public boolean isGenerateSummary() { return generateSummary; }
        public void setGenerateSummary(boolean generateSummary) { this.generateSummary = generateSummary; }
        
        public Integer getSummaryMaxLength() { return summaryMaxLength; }
        public void setSummaryMaxLength(Integer summaryMaxLength) { this.summaryMaxLength = summaryMaxLength; }
    }

    /**
     * 批量处理响应DTO
     */
    public static class BatchProcessResponse {
        private String htmlContent;
        private String tableOfContents;
        private Integer wordCount;
        private Integer readingTime;
        private String summary;

        // Getters and Setters
        public String getHtmlContent() { return htmlContent; }
        public void setHtmlContent(String htmlContent) { this.htmlContent = htmlContent; }
        
        public String getTableOfContents() { return tableOfContents; }
        public void setTableOfContents(String tableOfContents) { this.tableOfContents = tableOfContents; }
        
        public Integer getWordCount() { return wordCount; }
        public void setWordCount(Integer wordCount) { this.wordCount = wordCount; }
        
        public Integer getReadingTime() { return readingTime; }
        public void setReadingTime(Integer readingTime) { this.readingTime = readingTime; }
        
        public String getSummary() { return summary; }
        public void setSummary(String summary) { this.summary = summary; }
    }
}
